package com.anytrek.demomqtt.service;

import com.anytrek.demomqtt.config.MqttProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
@Log4j2
public class MQTTService {
    private final MqttPahoMessageHandler mqttOutboundHandler;
    private final MqttProperties mqttProperties;

    @Autowired
    public MQTTService(MqttPahoMessageHandler mqttPahoMessageHandler, MqttProperties mqttProperties) {
        this.mqttOutboundHandler = mqttPahoMessageHandler;
        this.mqttProperties = mqttProperties;
    }

    public void send(String message) {
        String[] topics = mqttProperties.getSubTopic().split(",");
        for (String topic : topics) {
            mqttOutboundHandler.handleMessage(
                    MessageBuilder.withPayload(message)
                            .setHeader(MqttHeaders.TOPIC, topic)
                            .build()
            );
            log.info("MQTT----->send topic : {}, SendMessage : {}", topic, message);
        }
    }
}